package persistence;

public class PersistenceSessionFactory {
	private PersistenceConfiguration pc;
	protected static ThreadLocal<PersistenceSession> currentSession = new ThreadLocal<PersistenceSession>();
	
	public PersistenceSessionFactory(PersistenceConfiguration pc) throws PersistenceException {
		this.pc = pc;
	}
	
	public PersistenceSession openSession() throws PersistenceException {
		PersistenceSession ps = new PersistenceSession(this);
		currentSession.set(ps);
		return ps;
	}
	
	public void close(PersistenceSession session) {
		//log.debug("Closing Persistence Session ");
		PersistenceSession current = currentSession.get();
		if (current != null && current == session) {
			currentSession.set(null);
		}
	}
	
	public PersistenceConfiguration getPersistenceConfiguration() {
		return this.pc;
	}
	
	public PersistenceSession getCurrentSession() throws PersistenceException {
		//log.debug("Getting current Persistence Session ");
		PersistenceSession session = currentSession.get();
		if(session == null) {
			session = openSession();
			currentSession.set(session);
		}
		return session;
	}
}
